package com.mytian.appstore.read;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mobile.auth.gatewayauth.AuthRegisterViewConfig;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;

public class LandscapeActivity extends AppCompatActivity {

    private Button mVaildBtn;
    private TextView mRetTV;
    private Button mLoginBtn;
    private Button mLoginDlgBtn;
    private Button mPreLoginBtn;
    private TokenResultListener mTokenListener;
    private String token;
    private ProgressDialog mProgressDialog;
    private PhoneNumberAuthHelper mAlicomAuthHelper;
    private static final int SERVICE_TYPE_AUTH = 1;//号码认证
    private static final int SERVICE_TYPE_LOGIN = 2;//一键登录
    private int mOldScreenOrientation;
    private int mScreenHeightDp;
    private int mScreenWidthDp;

    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    public void hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landscape);
        mVaildBtn = findViewById(R.id.vaild_button);
        mRetTV = findViewById(R.id.operator_name_tv);
        mLoginBtn = findViewById(R.id.login_button);
        mLoginDlgBtn = findViewById(R.id.login_dlg_button);
        mPreLoginBtn = findViewById(R.id.prelogin_button);
        init();
    }

    private void init() {

        /*
         *   1.init get token callback Listener
         */
        mTokenListener = new TokenResultListener() {

            @Override
            public void onTokenSuccess(final String ret) {
                LandscapeActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hideLoadingDialog();
                        /*
                         *   setText just show the result for get token。
                         *   use ret to verfiy number。
                         */
                        TokenRet tokenRet = JSON.parseObject(ret, TokenRet.class);
                        if (tokenRet != null) {
                            token = tokenRet.getToken();
                        }
                        if (tokenRet != null && ("600024").equals(tokenRet.getCode())) {
                            mRetTV.setText("终端自检成功:\n" + ret);
                        }

                        if (tokenRet != null && ("600001").equals(tokenRet.getCode())) {
                            mRetTV.setText("唤起授权页成功:\n" + ret);
                        }

                        if (tokenRet != null && ("600000").equals(tokenRet.getCode())) {
                            token = tokenRet.getToken();
                            mAlicomAuthHelper.quitLoginPage();
                            mRetTV.setText("获取token成功:\n" + ret);
                        }
                    }
                });
            }

            @Override
            public void onTokenFailed(final String ret) {
                LandscapeActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    /*
                     *  setText just show the result for get token
                     *  do something when getToken failed, such as use sms verify code.
                     */
                    hideLoadingDialog();
                    mAlicomAuthHelper.hideLoginLoading();
                    mRetTV.setText("失败:\n" + ret);
                }
            });
            }
        };

        /*
         *   2.init AlicomAuthHelper with tokenListener
         */
        mAlicomAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenListener);
        mAlicomAuthHelper.setAuthListener(mTokenListener);

        /*
         *   3.set debugMode when app is in debug mode, sdk will print log in debug mode
         */
        mAlicomAuthHelper.setLoggerEnable(true);
        mAlicomAuthHelper.setAuthSDKInfo("GB5bkZv3WqtQ7NojMheeEEysQm/bIW87XbN46NeYwGCNAyEV87mh+YQ8V8U1otRkaCT56MgDOzF0koPq4pWkYheV5iA4+yB/eyhyNrJFqC+y5pLfywBNfW1xhKDgrSFIJ8oi2uaQmwdT9L71MBW8Y8YJ4C86BsC7/Hr3CKVhi9OQ12M92jw58hIH3sV9uYiyleq8pvwu8xje9GXlBlCFMFQiIeRZ/tYnWv5QgCQVs4mfqmoVR3U8spziDV2YbHNCWob4DpjS+9iGV0PtK4CQEXPGNolEUfVbGpKEeoBQGfw=");

        /*
         *   使用一键登录传入 SERVICE_TYPE_LOGIN
         *   使用号码校验传入 SERVICE_TYPE_AUTH
         */
        mAlicomAuthHelper.checkEnvAvailable(SERVICE_TYPE_LOGIN);

        mVaildBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoadingDialog("正在获取认证token");
                mAlicomAuthHelper.getVerifyToken(5000);
            }
        });

        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                configLoginTokenLand();
                showLoadingDialog("正在请求登录Token");
                mAlicomAuthHelper.getLoginToken(LandscapeActivity.this, 5000);
            }
        });

        mLoginDlgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                configLoginTokenLandDialog();
                showLoadingDialog("正在请求登录Token");
                mAlicomAuthHelper.getLoginToken(LandscapeActivity.this, 5000);
            }
        });
    }

    private void configLoginTokenLand() {
        mAlicomAuthHelper.removeAuthRegisterXmlConfig();
        mAlicomAuthHelper.removeAuthRegisterViewConfig();
        mAlicomAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder()
                .setLayout(R.layout.custom_port_dialog_action_bar, new AbstractPnsViewDelegate() {
                    @Override
                    public void onViewCreated(View view) {
                        findViewById(R.id.tv_title).setVisibility(View.GONE);
                        findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mAlicomAuthHelper.quitLoginPage();
                            }
                        });
                    }
                })
                .build());

        int authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
        if (Build.VERSION.SDK_INT == 26) {
            mOldScreenOrientation = getRequestedOrientation();
            setRequestedOrientation(authPageOrientation);
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND;
        }

        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setAppPrivacyOne("《自定义隐私协议》", "https://www.baidu.com")
                .setAppPrivacyColor(Color.GRAY, Color.RED)
                .setPrivacyState(false)
                .setSwitchAccHidden(true)
                .setSloganHidden(true)
                .setNavHidden(true)
                .setStatusBarHidden(true)
                .setCheckboxHidden(false)
                .setLogoOffsetY(55)
                .setLogoImgPath("phone")
                .setLogoWidth(50)
                .setLogoHeight(50)
                .setNumFieldOffsetY(120)
                .setLogBtnOffsetY(166)
                .setLogBtnMarginLeftAndRight((mScreenHeightDp - 339) / 2)
                .setPrivacyMargin(115)
                .setLogBtnWidth(339)
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setPageBackgroundPath("page_background_color")
                .setScreenOrientation(authPageOrientation)
                .create());
    }

    private void updateScreenSize(int authPageScreenOrientation) {
        int screenHeightDp = AppUtils.px2dp(getApplicationContext(), AppUtils.getPhoneHeightPixels(LandscapeActivity.this));
        int screenWidthDp = AppUtils.px2dp(getApplicationContext(), AppUtils.getPhoneWidthPixels(LandscapeActivity.this));
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        if (authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_BEHIND) {
            authPageScreenOrientation = getRequestedOrientation();
        }
        if (authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                || authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
                || authPageScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE) {
            rotation = Surface.ROTATION_90;
        }
        switch (rotation) {
            case Surface.ROTATION_90:
                mScreenWidthDp = screenWidthDp;
                mScreenHeightDp = screenHeightDp;
                break;
        }
    }

    private View createLandDialogCustomSwitchView() {
        View v = LayoutInflater.from(this).inflate(R.layout.custom_switch_other, new RelativeLayout(this), false);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        v.setLayoutParams(layoutParams);
        return v;
    }

    private ImageView createLandDialogPhoneNumberIcon(int leftMargin) {
        ImageView imageView = new ImageView(this);
        int size = AppUtils.dp2px(this, 23);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(size, size);
        layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
        layoutParams.leftMargin = leftMargin;
        imageView.setLayoutParams(layoutParams);
        imageView.setBackgroundResource(R.drawable.phone);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        return imageView;
    }

    private void configLoginTokenLandDialog() {
        mAlicomAuthHelper.removeAuthRegisterXmlConfig();
        mAlicomAuthHelper.removeAuthRegisterViewConfig();
        int authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
        if (Build.VERSION.SDK_INT == 26) {
            mOldScreenOrientation = getRequestedOrientation();
            setRequestedOrientation(authPageOrientation);
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND;
        }
        updateScreenSize(authPageOrientation);
        final int dialogWidth = (int) (mScreenWidthDp * 0.63);
        final int dialogHeight = (int) (mScreenHeightDp * 0.6);
        final int logBtnOffsetY = dialogHeight / 2 - 50;
        final View switchContainer = createLandDialogCustomSwitchView();
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) switchContainer.findViewById(R.id.container_other).getLayoutParams();
        layoutParams.width = AppUtils.dp2px(LandscapeActivity.this, dialogWidth / 2 - 60);

        mAlicomAuthHelper.addAuthRegistViewConfig("image_icon",
                new AuthRegisterViewConfig.Builder()
                        .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_NUMBER)
                        .setView(createLandDialogPhoneNumberIcon(AppUtils.dp2px(getApplicationContext(), 30)))
                        .build());

        mAlicomAuthHelper.addAuthRegistViewConfig("switch_other", new AuthRegisterViewConfig.Builder()
                .setRootViewId(AuthRegisterViewConfig.RootViewId.ROOT_VIEW_ID_NUMBER)
                .setView(switchContainer).build());

        mAlicomAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder()
                .setLayout(R.layout.custom_land_dialog, new AbstractPnsViewDelegate() {
                    @Override
                    public void onViewCreated(View view) {
                        findViewById(R.id.tv_title).setVisibility(View.GONE);
                        findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mAlicomAuthHelper.quitLoginPage();
                            }
                        });
                        int iconTopMargin = AppUtils.dp2px(getContext(), logBtnOffsetY + 50);
                        View iconContainer = findViewById(R.id.container_icon);
                        RelativeLayout.LayoutParams iconLayout = (RelativeLayout.LayoutParams) iconContainer.getLayoutParams();
                        iconLayout.topMargin = iconTopMargin;
                        iconLayout.width = AppUtils.dp2px(getContext(), dialogWidth / 2 - 60);
                    }
                })
                .build());

        mAlicomAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setAppPrivacyOne("《自定义隐私协议》", "https://www.baidu.com")
                .setAppPrivacyColor(Color.GRAY, Color.RED)
                .setNavHidden(true)
                .setCheckboxHidden(true)
                .setLogoHidden(true)
                .setSloganHidden(true)
                .setSwitchAccHidden(true)
                .setNumberFieldOffsetX(60)
                .setNumberLayoutGravity(Gravity.LEFT)
                .setNumberSize(24)
                .setNumFieldOffsetY(logBtnOffsetY - 35)
                .setPrivacyOffsetY_B(20)
                .setPageBackgroundPath("dialog_page_background")
                .setLogBtnOffsetY(logBtnOffsetY)
                .setLogBtnOffsetX(30)
                .setLogBtnMarginLeftAndRight(0)
                .setLogBtnWidth(174)
                .setLogBtnLayoutGravity(Gravity.LEFT)
                .setLogBtnHeight(51)
                .setDialogWidth(dialogWidth)
                .setDialogHeight(dialogHeight)
                .setDialogBottom(false)
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setProtocolGravity(Gravity.CENTER_VERTICAL)
                .setScreenOrientation(authPageOrientation)
                .create());
    }
}
